package com.example.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
    private static final Logger logger = LoggerFactory.getLogger(DBUtil.class);
    private static final String URL = "jdbc:mysql://localhost:3306/user_db?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            logger.info("MySQL驱动加载成功");
        } catch (ClassNotFoundException e) {
            logger.error("MySQL驱动加载失败: {}", e.getMessage(), e);
        }
    }

    public static Connection getConnection() throws SQLException {
        try {
            Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            logger.info("数据库连接成功");
            return conn;
        } catch (SQLException e) {
            logger.error("数据库连接失败: {}", e.getMessage(), e);
            throw e;
        }
    }

    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
                logger.debug("ResultSet已关闭");
            }
            if (ps != null) {
                ps.close();
                logger.debug("PreparedStatement已关闭");
            }
            if (conn != null) {
                conn.close();
                logger.debug("Connection已关闭");
            }
        } catch (SQLException e) {
            logger.error("关闭数据库资源时发生错误: {}", e.getMessage(), e);
        }
    }
} 